// 创建座位
let arrColumn

function createSeat(arr) {
    let seats_box = document.querySelector("#seats_box");
    let row = 1;
    let column = 0;
    arrColumn = arr[arr.length - 1].seatColumn;
    let str = `<div class="row">`;
    for (let k = 0; k < arr.length; k++) {
        column += 1;
        if (k % arrColumn == 0 && k != arr.length - 1 && k != 0) {
            row += 1;
            column = 1;
            str += `</div><div class="row">`;
        }
        if (arr[k].type == 0) {
            str += `<span class="seat empty" seat-id="${arr[k].id}" data-column-id="" data-row-id="${row - 1}"></span>`;
            continue;
        } else if (arr[k].status == 1) {
            str += `<span class="seat sold" seat-id="${arr[k].id}" data-column-id="${column - 1}" data-row-id="${row - 1}"></span>`;
        } else if (arr[k].type == 1) {
            str += `<span class="seat selectable" onclick="toSelect(this)" seat-id="${arr[k].id}" data-column-id="${column - 1}" data-row-id="${row - 1}"></span>`;
        }
    }
    str += `</dev>`
    seats_box.innerHTML = str;
}

// 创建右侧电影信息
function showMovieInfo(movieDate) {

    let str = '';
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl + '/devs/type',
        async: false,
        data: {movieId: movieDate.id},
        success: function (result) {
            if (result.code == 200) {
                let typeData = result.data;
                for (let i in typeData) {
                    if (typeData[i] == 1 && i != 'id' && 1 != 'movieId') {
                        switch (i) {
                            case 'love':
                                str += "爱情,";
                                break;
                            case 'comedy':
                                str += "喜剧,";
                                break;
                            case 'animation':
                                str += "动画,";
                                break;
                            case 'story':
                                str += "剧情,";
                                break;
                            case 'horror':
                                str += "恐怖,";
                                break;
                            case 'frightened':
                                str += "惊悚,";
                                break;
                            case 'science_fiction':
                                str += "科幻,";
                                break;
                            case 'action':
                                str += "动作,";
                                break;
                            case 'suspense':
                                str += "悬疑,";
                                break;
                            case 'crime':
                                str += "犯罪,";
                                break;
                            case 'adventure':
                                str += "冒险,";
                                break;
                            case 'warfare':
                                str += "战争,";
                                break;
                            case 'strange':
                                str += "奇幻,";
                                break;
                            case 'movement':
                                str += "运动,";
                                break;
                            case 'family':
                                str += "家庭,";
                                break;
                            case 'ancient_costume':
                                str += "古装,";
                                break;
                            case 'swordsman':
                                str += "武侠,";
                                break;
                            case 'west':
                                str += "西部,";
                                break;
                            case 'history':
                                str += "历史,";
                                break;
                            case 'special_note':
                                str += "传记,";
                                break;
                            case 'song_dance':
                                str += "歌舞,";
                                break;
                            case 'film_noir':
                                str += "黑色电影,";
                                break;
                            case 'shorts':
                                str += "短片,";
                                break;
                            case 'documentary':
                                str += "纪录片,";
                                break;
                            case 'traditional':
                                str += "戏曲,";
                                break;
                            case 'music':
                                str += "音乐,";
                                break;
                            case 'calamity':
                                str += "灾难,";
                                break;
                            case 'youth':
                                str += "青春,";
                                break;
                            case 'children':
                                str += "儿童,";
                                break;
                            case 'anime':
                                str += "动漫,";
                                break;
                            case 'other':
                                str += "其他,";
                                break;
                        }
                    }
                }
            } else {
                console.log();
            }
        }
    })
    str = str.substr(0, str.length - 1);
    document.getElementById("types").innerText = str;
    document.getElementsByClassName("name text-ellipsis")[0].innerText = movieDate.title;
    document.getElementById("duration").innerText = `${movieDate.duration} 分钟`;
    spanMovieInfo[2].innerText = movieDate.language;
    price = movieDate.price;
    temp = movieDate.price;
    spanMovieInfo[4].innerText = `￥${price}/张`;
}

// 选座数
let num;
// 票价
let price;
// 价格
let spanPrice = document.querySelector(".price")
// 优惠金额
let couponMoney = 0;
// 优惠卷id
let couponId = null;
// 被选择的优惠卷
let couponSelected = null;

// 被选的座位对象
let selectedNum = null;

// 判断是购票还是离开页面
let leaveFlag = true;

// 用户离开更新选座状态
function userOut() {
    let allSelectedSeat = document.getElementsByClassName("selected")
    let allSelectedSeatId = []
    for (let i = 0; i < allSelectedSeat.length; i++) {
        allSelectedSeatId.push(allSelectedSeat[i].getAttribute("seat-id"))
    }
    $.ajax({
        url: serverConfig.serverUrl + `/devs/seat/end/${userInfo.id}/${allSelectedSeatId}/${sessionData.id}`,
        type: 'post',
    })
}

// 选座
function toSelect(obj) {

    // 被选的座位Id
    let seatId = obj.getAttribute("seat-id");
    let row = obj.getAttribute("data-row-id");
    let column = obj.getAttribute("data-column-id")
    selectedNum = document.querySelectorAll(".selected");

    // 更改座位颜色
    let show_seat = document.querySelector(".ticket-container");
    let noTicket = document.querySelector(".no-ticket");
    let text = document.querySelector(".text");

    // 被选中
    if (obj.className == 'seat selectable' && selectedNum.length <= 5) {
        // 发送wabsocket更新座位选中状态
        $.ajax({
            url: serverConfig.serverUrl + `/devs/seat/${userInfo.id}/${seatId}/${0}/${sessionData.id}`,
            type: 'post',
        })
        text.style.display = ""
        obj.className = 'seat selected';

        // 取消右侧选座提示
        noTicket.style.display = "none";

        // 右侧显示具体座位号
        let span = document.createElement("span");
        span.innerHTML = `<span class="ticket" data-row-id="${row}" data-column-id="${column}" data-index="${row}-${column}">${parseInt(row) + 1}排${parseInt(column) + 1}座</span>`
        show_seat.appendChild(span);
        // 重新获取选中的座位
        selectedNum = document.querySelectorAll(".selected");
        // 取消选中
    } else if (obj.className == 'seat selected') {

        //发送wabsocket更新座位选中状态
        $.ajax({
            url: serverConfig.serverUrl + `/devs/seat/${userInfo.id}/${seatId}/${-1}/${sessionData.id}`,
            type: 'post',
        })

        let spans = document.querySelectorAll(".ticket");
        let spanRow;
        let spanColum;
        for (let i = 0; i < spans.length; i++) {
            spanRow = spans[i].getAttribute("data-row-id");
            spanColum = spans[i].getAttribute("data-column-id");
            if (row == spanRow && column == spanColum) {
                spans[i].remove();
                if (document.querySelectorAll(".ticket").length == 0) {
                    // 显示右侧选座提示
                    text.style.display = "none"
                    noTicket.style.display = "";
                }
            }
        }
        obj.className = 'seat selectable';

        // 重新获取选中的座位
        selectedNum = document.querySelectorAll(".selected");
        // 选座最多只能选6个
    } else {
        let prompt = document.querySelector(".modal-container");
        let tip = document.querySelector(".tip");
        tip.innerText = "一次最多购买六张票";
        prompt.style.display = '';
        return;
    }

    // 计算选座位数
    num = selectedNum.length
    totalPrice()
}


// 获取所有选座信息（已选 + 被选）
function getTotalSeat(objArr, totalSeat) {
    let size = totalSeat.length
    for (let i = 0; i < objArr.length; i++) {
        let selectedRow = objArr[i].getAttribute("data-row-id");
        let selectedColumn = objArr[i].getAttribute("data-column-id");
        let seatArr1 = new Array();
        seatArr1[0] = selectedRow;
        seatArr1[1] = selectedColumn;
        totalSeat[i + size] = seatArr1;
    }
    return totalSeat;
}

// 检查选座是否隔空
function checkSeat(column) {

    // 获取所有选座信息（已选 + 被选）
    let selectedNum = document.querySelectorAll(".selected");
    for (let i = 0; i < selectedNum.length; i++) {

        // seatRow[i] = selectedNum[i].getAttribute("data-row-id")
        let selectedElement = selectedNum[i];
        let index = selectedElement.getAttribute("data-column-id")
        let rowClass = selectedElement.parentElement;

        let left_1 = rowClass.children[index - 1];
        let right_1 = rowClass.children[index - (-1)];

        let left_2 = rowClass.children[index - 2];
        let right_2 = rowClass.children[index - (-2)];

        if (index - 1 < 0 || index - (-1) == column) {

            console.log("走廊 合格")
        } else if (index - 2 < 0) {
            if ((left_1.className == "seat empty" || left_1.className == "seat selected" || left_1.className == "seat sold") || (right_1.className == "seat empty") || (right_1.className == "seat orther_seat") || (left_1.className == "seat orther_seat")) {
                console.log("左走廊 合格")
            } else {
                console.log("左走廊 不合格")
                return false;
            }
        } else if (index - (-2) == column) {
            if (right_1.className == "seat empty" || (right_1.className == "seat sold") || (right_1.className == "seat selected") || left_1.className == "seat selected") {
                console.log("右走廊 合格")
            } else {
                console.log("右走廊 不合格")
                return false;
            }
        } else {

            if (left_2.className == "seat empty" && left_1.className == "seat empty") {
                console.log("靠左走廊 合格")
            } else if (right_1.className == "seat sold" || left_1.className == "seat sold") {
                console.log("左或右有人 合格")
            } else if ((left_2.className == "seat empty" && left_1.className == "seat selectable") && (right_1.className == "seat selectable")) {
                console.log(selectedNum[i])
                console.log("靠左走廊 左侧有空 不合格")
                return false;
            } else if ((left_2.className == "seat selectable" && left_1.className == "seat selectable")
                && ((right_2.className == "seat empty" && right_1.className == "seat empty")
                    || (right_2.className == "seat selectable" && right_1.className == "seat selectable"))) {

                console.log("靠左走廊 左侧有两空 合格 同时满足右边")
            } else if ((left_2.className == "seat selectable" && left_1.className == "seat selectable")
                && ((right_2.className == "seat empty" && right_1.className == "seat selectable")
                    || (right_2.className == "seat sold" && right_1.className == "seat selectable")
                    || (right_1.className != "seat selected"))) {
                console.log(selectedNum[i])
                console.log("靠左走廊 左侧有两空 不合格 没有满足右边")
                return false;
            } else if ((left_2.className == "seat sold" && left_1.className == "seat selectable") && right_2.className != "seat empty") {
                // && (right_1.className != "seat selectable")
                console.log(selectedNum[i])
                console.log("左左有人 左侧有空 不合格")
                return false;
            } else if (right_2.className == "seat empty" && right_1.className == "seat empty") {
                console.log("靠右走廊 合格")
            } else if ((right_2.className == "seat empty" && right_1.className == "seat selectable") && (left_1.className != "seat selected")) {
                console.log(selectedNum[i])
                console.log("靠右走廊 右侧有空 不合格")
                return false;
            } else if (right_2.className == "seat selectable" && right_1.className == "seat selectable") {
                console.log("靠右走廊 右侧有两空 合格 1")
            } else if (right_2.className == "seat sold" && right_1.className == "seat selectable" && left_1.className != "seat selected") {
                console.log(selectedNum[i])
                console.log("右右有人 右侧有空 不合格")
                return false;
            } else if ((right_1.className == "seat selectable" && right_2.className == "seat selected")) {
                if (index - (-3) == column) {
                    console.log("合格")
                } else {
                    console.log(selectedNum[i])
                    console.log("不合格")
                    return false;
                }
            }
        }
        if (index - 1 < 0 || index - (-1) == column) {
            // console.log("走廊 合格")
        } else if ((left_2.className != "seat selectable") && left_1.className == "seat selectable" && right_1.className == "seat selected" && right_2.className == "seat selected") {
            if (index - (-3) == column) {
                console.log("合c格")
            } else if (index - (-3) < column && rowClass.children[index - (-2)].className == "seat selectable") {
                console.log(selectedNum[i])
                console.log("选座不连续 + 3")
                return false;
            }
        } else if (index - 2 < 0 || index - (-2) == column) {
            if ((left_1.className == "seat selectable" || right_1.className == "seat selectable") && (right_1.className != "seat selected") && (left_1.className != "seat selected") && (right_1.className != "seat empty") && (right_1.className != "seat sold")) {
                console.log(selectedNum[i])
                console.log("选座不连续,与走廊空一格")
                return false;
            }
        } else if (left_1.className == "seat selectable" && left_2.className != "seat selectable" && (left_2.className != "seat sold") && right_1.className != "seat selected" && right_1.className != "seat sold" && right_1.className != "seat empty") {
            console.log(selectedNum[i])
            console.log("选座不连续,左边座位间空一格")
            return false;
        } else if (right_1.className == "seat selectable" && right_2.className != "seat selectable" && (left_2.className != "seat sold") && left_1.className != "seat selected" && left_1.className != "seat empty" && left_1.className != "seat sold") {
            console.log(selectedNum[i])
            console.log("选座不连续,右边座位间空一格")
            return false;
        } else if (left_1.className == "seat selectable" && left_2.className == "seat empty" && right_1.className != "seat selectable" && right_1.className != "seat sold" && right_1.className != "seat selected") {
            console.log(selectedNum[i])
            console.log("选座不连续,左边边座位间空一格 满足右边")
            return false;
        } else if (index - 2 >= 0 && right_1.className == "seat selectable" && right_2.className == "seat sold") {
            if (left_1.className == "seat selected" && left_2.className == "seat selectable") {
                console.log(selectedNum[i])
                console.log("选座不连续 + 1")
                return false;
            }
        } else if ((left_2.className != "seat selectable") && left_1.className == "seat selectable" && right_1.className == "seat selected" && right_2.className == "seat selectable") {
            console.log(selectedNum[i])
            console.log("选座不连续 + 2")
            return false;
        } else {
            console.log("选座合格")
        }
    }
    return true;
}

// 生成购票数据
function check() {
    let seatIds = [];
    let seatObj = document.getElementsByClassName("seat selected")
    for (let i = 0; i < seatObj.length; i++) {
        seatIds.push(seatObj[i].getAttribute("seat-id"))
    }
    return {
        id: null,
        number: createordernum(),
        userId: userInfo.id,
        realName: userInfo.realName,
        phone: userInfo.phone,
        movieId: movieDate.id,
        movieTitle: movieDate.title,
        posterImg: movieDate.posterImg,
        moviePrice: movieDate.price,
        quota: num,
        total: num * movieDate.price - couponMoney,
        sessionId: sessionData.id,
        startTime: sessionData.startTime,
        status: 0,
        createTime: new Date().toLocaleString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}).replace(/[^\\d]/g, ''),
        couponId: couponId,
        couponMoney: couponMoney,
        seatId: seatIds
    };
}

// 购票请求
function payBtn() {
    if (selectedNum == null) {
        let prompt = document.querySelector(".modal-container");
        let tip = document.querySelector(".tip");
        tip.innerText = "请先选座!!";
        prompt.style.display = '';
	return;
    }

    // 判断是否隔空选
    if (!checkSeat(arrColumn)) {
        let prompt = document.querySelector(".modal-container");
        let tip = document.querySelector(".tip");
        tip.innerText = "不能隔空选！！";
        prompt.style.display = '';
    } else {
        // 生成购票数据
        let orderDTO = check();
        // 发送添加订单请求
        $.ajax({
            headers: {
                "token": localStorage.getItem("token")
            },
            type: 'post',
	    dataType: 'json',
	    contentType: 'application/json',
            url: serverConfig.serverUrl + '/devs/order',
            data: JSON.stringify(orderDTO),
	    traditional: true,
            success: function (result) {
                if (result.code == 200) {
                    leaveFlag = false;
                    localStorage.setItem("orderId", result.data);

                    window.location.href = `../html/pay_wait.html`;
                } else {
                    console.log(result)
                }
            }
        })

    }
}

// 随机生成订单
function setTimeDateFmt(s) {  // 个位数补齐十位数
    return s < 10 ? '0' + s : s;
}

// 随机生成订单
function createordernum() {
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = setTimeDateFmt(month)
    day = setTimeDateFmt(day)
    hour = setTimeDateFmt(hour)
    minutes = setTimeDateFmt(minutes)
    seconds = setTimeDateFmt(seconds)
    return now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    // 基于年月日时分秒+随机数生成订单编号
}

let temp;

// 计算总价
function totalPrice(obj) {
    price = temp;
    if (userInfo.memberId != null) {
        price = price * 0.9;
        document.querySelector("#huiyuan").innerText = "已使用会员优惠";

    }

    couponSelected = document.getElementsByClassName("couponSelected")[0];

    if (obj != null && (num == null || num == 0)) {
        layer.msg('请先选座!', {icon: 2})
    } else if (couponSelected != null && obj != null) {
        // 切换优惠卷
        obj.children[0].innerText = `已使用`;
        couponId = obj.getAttribute("couponId")
        couponSelected.className = "coupon-box-right";
        couponSelected.children[0].innerText = `使用`;
        obj.className = "coupon-box-right couponSelected";
        if (couponSelected == obj) {
            couponMoney = 0;
        } else {
            couponMoney = document.getElementsByClassName("couponSelected")[0].parentElement.children[0].children[0].innerText;
        }
        spanPrice.innerText = price * (num) - couponMoney;
    } else if (obj == null) {
        // 不使用优惠卷
        spanPrice.innerText = price * (num) - couponMoney;
    } else {
        // 第一次使用优惠卷
        obj.children[0].innerText = `已使用`;
        couponId = obj.getAttribute("couponId")
        // couponSelected.innerText = `使用`;
        obj.className = "coupon-box-right couponSelected";
        couponMoney = obj.parentElement.children[0].children[0].innerText;
        spanPrice.innerText = price * (num) - couponMoney;
    }

    if (num == 0) {
        document.querySelector("#huiyuan").innerText = "";

        couponMoney = 0;
        if (!couponSelected) {
            
        } else {
            couponSelected.className = "coupon-box-right";
            couponSelected.children[0].innerText = `使用`;
        }
        spanPrice.innerText = 0
    }
}

// 关闭弹框提示
function toNone() {
    let prompt = document.querySelector(".modal-container")
    prompt.style.display = 'none';
}

// 获取当前登录用户
function getUserInfo() {

    $.ajax({
        headers: {
            "token": localStorage.getItem("token")
        },
        type: 'get',
        url: serverConfig.serverUrl + '/devs/user',
        async: false,
        success: function (result) {
            if (result.code == 200)
                userInfo = result.data;
            else
                window.location.href = '../html/login.html'
        }
    })
    if (userInfo.memberId != null) {
        document.querySelector("#huiyuan").innerText = "";
    }
    return userInfo;
}

let spanMovieInfo = document.getElementsByClassName("value text-ellipsis");
let sessionData;
let userInfo;
$(function () {

    // 获取当前登录用户
    userInfo = getUserInfo();

    if (userInfo == null) {
        window.location.href = "../html/login.html";
        return;
    }
    // 加密手机号
    $(".phone-num").text(userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'));

    let sessionId = window.location.search.substr(0).split("=")[1];

    // 获取场次信息
    $.ajax({
        type: 'get',
        url:serverConfig.serverUrl + '/devs/session',
        async: false,//异步加载
        data: {id: sessionId},
        success: function (result) {
            if (result.code == 200) {
                sessionData = result.data;
                spanMovieInfo[1].innerText = sessionData.hallType;
                spanMovieInfo[3].innerText = sessionData.starTime;
            } else {
                console.log("");
            }
        }
    })

    // 获取座位信息
    let sessionIdData = {sessionId: sessionId}
    let seatDate = [];
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl +'/devs/seat',
        async: false,
        data: sessionIdData,
        success: function (result) {
            if (result.code == 200) {
                seatDate = result.data;
            } else {
                console.log("");
            }
        }
    })
    createSeat(seatDate)

    // 获取电影信息
    let movieIdData = {id: sessionData.movieId}
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl +'/devs/movie/findById',
        async: false,
        data: movieIdData,
        success: function (result) {
            if (result.code == 200) {
                movieDate = result.data;
            } else {
                console.log("");
            }
        }
    })
    showMovieInfo(movieDate)

    // 加载优惠卷请求
    $(function () {
        layui.use('flow', function () {
            var flow = layui.flow;

            flow.load({
                elem: '#LAY_demo1' // 流加载容器
                ,
                scrollElem: '#a' // 滚动条所在元素，一般不用填，此处只是演示需要。
                ,
                done: function (page, next) { // 执行下一页的回调
                    var lis = [];

                    // 模拟数据插入
                    setTimeout(function () {
                        // console.log(0)
                        let couponPageInfo;
                        let couponData;

                        $.ajax({
                            type: 'get',
                            url: serverConfig.serverUrl +'/devs/coupon',
                            data: {userId: userInfo.id, status: 0, pageNum: page, pageSize: 3},
                            async: false,// 异步加载
                            success: function (reulst) {
                                if (reulst.code == 200) {

                                    couponPageInfo = reulst.data;
                                    couponData = couponPageInfo.list;
                                } else {
                                    couponPageInfo = []
                                    console.log(reulst)
                                }
                            }
                        })


                        for (var i = 0; i < couponPageInfo.size; i++) {
                            lis.push(`<li>
                                    <div class="coupon-box m_t30" >
                                        <div class="coupon-box-left">
                                            <span class="couponMoney">${couponData[i].money}</span><span class="yuan">元</span>
                                            <span class="coupon_ditle">${couponData[i].illustrate}</span>
                                        </div>
                                        <div class="coupon-box-right" onclick="totalPrice(this)" couponId="${couponData[i].id}">
                                            <span class="use_coupon" >使   用</span>
                                        </div>
                                    </div>
                            </li>`)
                        }
                        // 执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
                        // pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
                        next(lis.join(''), page < couponPageInfo.pages); //假设总页数为 10
                    }, 500);
                }
            });
        });
    })

    // 显示优惠卷
    let waringBtn = document.getElementsByClassName("layui-btn layui-btn-radius layui-btn-danger")[0].parentElement;

    let cha = document.getElementById("cha");
    let a = document.getElementById("adid");

    cha.addEventListener("click", function () {
        $(a).css("display", "none")
    })
    waringBtn.onmouseout = function () {

        $(a).css("display", "none")
    }
    waringBtn.onmousemove = function () {
        $(a).css("display", "");
    }
    a.onmousemove = function () {
        $(a).css("display", "");
    }
})

$(function () {
    let ws;
    // 检测浏览器是否支持webSocket
    if ("WebSocket" in window) {
        $("#content").html("您的浏览器支持webSocket!");
        // 模拟产生clientID

        // 创建 WebSocket 对象,注意请求路径！！！！
        // 部署的时候,需要修改成真实的ip地址
        ws = new WebSocket("ws://118.178.105.195:8088/dev/tt/" + userInfo.id + "/" + sessionData.id);

        // 与服务端建立连接时触发
        ws.onopen = function () {
	    console.log("你好服务端！我是客户端seat" + userInfo.id)

            // 模拟发送数据到服务器
            ws.send("你好服务端！我是客户端seat" + userInfo.id);

        }
        // 接收到服务端消息时触发
        ws.onmessage = function (evt) {
            let received_msg = evt.data;
            let ortherUserId = received_msg.split(" ")[0];
            let ortherSeatId = received_msg.split(" ")[1];
            let ortherStatus = received_msg.split(" ")[2];

            if (ortherUserId != userInfo.id) {
                let allSeat = document.getElementsByClassName("seat");
                for (let i = 0; i < allSeat.length; i++) {
                    if (allSeat[i].getAttribute("seat-id") == ortherSeatId) {
                        let seat = allSeat[i];
                        if (ortherStatus == -1) {
                            seat.className = "seat selectable";
                            seat.setAttribute("onclick", "onclick=toSelect(this)")
                        } else if (ortherStatus == 2) {
                            seat.className = "seat sold"
                            seat.setAttribute("onclick", "");
                        } else {
                            seat.className = "seat orther_seat"
                            seat.setAttribute("onclick", "ortherSelect(this)")
                        }
                    }
                }
            } else {
            }
        };

        // 服务端关闭连接时触发
        ws.onclose = function () {
            let allSelectedSeat = document.getElementsByClassName("selected")
            let allSelectedSeatId = []
            for (let i = 0; i < allSelectedSeat.length; i++) {
                allSelectedSeatId.push(allSelectedSeat[i].getAttribute("seat-id"))
            }

            $.ajax({
                url: serverConfig.serverUrl + `/devs/seat/end/${userInfo.id}/${allSelectedSeatId}/${sessionData.id}`,
                type: 'post',
            })
            console.error("连接已经关闭.....")
        };
    } else {
        $("#content").html("您的浏览器不支持webSocket！");
    }
})

// 离开页面
window.addEventListener('beforeunload', function (e) {
    if (leaveFlag) {
        userOut()
    }
})

// 页面刚加载
$(function () {
    $.ajax({
        url:serverConfig.serverUrl + `/devs/seat/first/${sessionData.id}`,
        type: 'post',
        success: function (result) {
            if (result.code == 200) {

                let seatId = []
                let changeArr = []
                seatId = result.data;

                let allSeat = document.getElementsByClassName("seat selectable");

                for (let i = 0; i < allSeat.length; i++) {
                    let tageter = allSeat[i]

                    if (seatId.indexOf(parseInt(tageter.getAttribute("seat-id"))) != -1) {
                        changeArr.push(tageter)
                    }
                }
                for (let i = 0; i < changeArr.length; i++) {
                    let seat = changeArr[i];
                    seat.className = "seat orther_seat"
                    seat.setAttribute("onclick", "ortherSelect(this)")
                }
            } else {

            }
        }
    })
})

// 点击别人的座位
function ortherSelect() {
    layer.msg('别人正在选座哟!', {icon: 2})
}



